#

if grep -iEq 'alpine' /etc/issue || grep -iEq 'alpine' /etc/*-release
then
  echo 'linux is alpine'
  if [ -h /usr/bin/pwsh ]
  then
    echo 'powershell installed on alpine'
    if grep -Eq 'powershell' /etc/ssh/sshd_config
    then
      echo 'powershell_sshd_good'
      exit 0
    else
      echo '' >>  /etc/ssh/sshd_config
      echo 'Subsystem powershell /usr/bin/pwsh -sshs -NoLogo -NoProfile' >>  /etc/ssh/sshd_config
      echo 'UseDNS no' >>  /etc/ssh/sshd_config
      echo 'PermitRootLogin yes' >>  /etc/ssh/sshd_config
      rc-service sshd restart
      echo 'powershell_sshd_fixed'
      exit 0
    fi
  else
    echo 'installing powershell now'
    apk update
    apk add --no-cache \
    ca-certificates \
    less \
    ncurses-terminfo-base \
    krb5-libs \
    libgcc \
    libintl \
    libssl1.1 \
    libstdc++ \
    tzdata \
    userspace-rcu \
    zlib \
    icu-libs \
    curl \
    lttng-ust \
    aria2

    cd /tmp
    mkdir  -p /opt/microsoft/powershell/7

    for i in `seq 1 20`
    do
      DOWNLOAD=`curl -L 'https://api.github.com/repos/powershell/powershell/releases/latest' -H "Accept: application/vnd.github.v4.full+json" |grep -i 'browser_download_url' |grep -i 'alpine-x64' | awk -F '"' '{print $4}'`
      if [ -z "${DOWNLOAD}" ]
      then
        echo '获取pwsh安装网址失败！'
        sleep 3
      else
        echo ${DOWNLOAD}
        GET_DOWNLOAD=1
        break
      fi
    done

    if ((GET_DOWNLOAD=1))
    then
      echo '获取pwsh安装网址成功！'
    else
      echo '多次获取pwsh安装网址失败！脚本退出！'
      exit 1
    fi

    rm -rf /tmp/powershell*.tar.gz
    for i in `seq 1 6`
    do
      aria2c  --split=9  --max-connection-per-server=9  --continue=true ${DOWNLOAD}
      if [ $? -eq 0 ]
      then
        DOWNLOAD_END=1
        break
      else
        echo '下载pwsh失败！'
        sleep 1
      fi
    done

    if ((DOWNLOAD_END=1))
    then
      echo '下载pwsh成功！'
    else
      echo '多次下载pwsh失败！脚本退出！'
      exit 2
    fi

    DDDD=`find /tmp -iname 'powershell*.tar.gz'`
    echo $DDDD
    tar -C /opt/microsoft/powershell/7 -xf ${DDDD}

    if [ -x /opt/microsoft/powershell/7/pwsh ]
    then
      ln -s /opt/microsoft/powershell/7/pwsh /usr/bin/pwsh
    else
      echo '安装pwsh失败！脚本退出！'
      exit 4
    fi

    if grep -Eq 'powershell' /etc/ssh/sshd_config
    then
      echo 'powershell_sshd_good'
      exit 0
    else
      echo '' >>  /etc/ssh/sshd_config
      echo 'Subsystem powershell /usr/bin/pwsh -sshs -NoLogo -NoProfile' >>  /etc/ssh/sshd_config
      echo 'UseDNS no' >>  /etc/ssh/sshd_config
      echo 'PermitRootLogin yes' >>  /etc/ssh/sshd_config
      rc-service sshd restart
      echo 'powershell_sshd_fixed'
      exit 0
    fi

  fi
else
  echo 'linux not alpine'
  exit 3
fi




